<!--
 * @Author: huzf
 * @Date: 2024-03-06 09:39:00
 * @Descripttion: 
-->
<template>
  <input type="file" @change="changeUpload" />
  <div id="sheet-wrapper">
    <div id="x-spreadsheet-demo"></div>
  </div>
</template>
<script setup>
import {
  onMounted,
  ref,
  onUnmounted,
  getCurrentInstance,
  reactive,
  toRefs,
} from "vue";
import Spreadsheet from "x-data-spreadsheet";
import { read, utils, writeFileXLSX } from "xlsx";
import { ElLoading } from "element-plus";
import zhCN from "x-data-spreadsheet/src/locale/zh-cn";
Spreadsheet.locale("zh-cn", zhCN);
const { proxy } = getCurrentInstance();
const dataLoading = ref(false);
const data = reactive({
  currentXs: null,
  originWb: null,
});
const { currentXs, originWb } = toRefs(data);
const emit = defineEmits(["loadSuccess"]);
onMounted(() => {
  loadSpreadsheet(undefined);
});
function changeUpload(e) {
  const file = e.target.files[0];
  loadFile(file);
}

function loadFile(file) {
  console.log("🚀 ~ loadFile ~ file:", file);
  const reader = new FileReader();
  let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
  let istxtorcsv = fileType == "txt" || fileType == "csv";
  reader.onload = function (event) {
    const arrayBuffer = event.target.result;
    // console.log('🚀 ~ loadFile ~ arrayBuffer:', arrayBuffer)
    const wb = istxtorcsv
      ? read(arrayBuffer, { type: "string" })
      : read(arrayBuffer);
    console.log("🚀 ~ loadFile ~ wb:", wb);
    currentXs.value = null;
    loadSpreadsheet(wb);
  };
  if (istxtorcsv) {
    reader.readAsText(file, "utf-8");
  } else {
    reader.readAsArrayBuffer(file);
  }
}

function loadSpreadsheet(wb, dispatchEmit = true) {
  document.getElementById("x-spreadsheet-demo").innerHTML = "";
  let maxLen = wb
    ? Math.max(...stox(wb).map((it) => Object.keys(it.rows).length))
    : 0;
  let maxColLen = wb
    ? Math.max(
        ...stox(wb).map(
          (it) => Object.keys(Object.values(it.rows)[0].cells).length
        )
      )
    : 26;

  maxLen = maxLen < 100 ? 100 : maxLen;
  maxColLen = maxColLen < 26 ? 26 : maxColLen;
  const s = new Spreadsheet("#x-spreadsheet-demo", {
    mode: "edit", // edit | read
    showToolbar: false,
    showBottomBar: false,
    showContextmenu: true,
    view: {
      height: () => document.getElementById("sheet-wrapper")?.clientHeight,
      width: () => document.getElementById("sheet-wrapper")?.clientWidth,
    },
    row: {
      len: maxLen,
    },
    col: {
      len: maxColLen,
    },
  })
    .loadData(wb ? stox(wb) : {}) // load data
    .change((data) => {
      console.error("🚀 ~ .change ~ data:", data);
      // save data to db
    });

  // data validation
  s.validate();
  currentXs.value = s;
  s.on("cell-selected", (cell, ri, ci) => {
    console.log("🚀 ~ s.on ~ cell, ri, ci:", cell, ri, ci);
  });

  originWb.value = wb;
  if (dispatchEmit) emit("loadSuccess");
}

function xtos(sdata) {
  var out = utils.book_new();
  sdata.forEach(function (xws) {
    var aoa = [[]];
    var rowobj = xws.rows;
    for (var ri = 0; ri < rowobj.len; ++ri) {
      var row = rowobj[ri];
      if (!row) continue;
      aoa[ri] = [];
      row?.cells &&
        Object.keys(row.cells).forEach(function (k) {
          var idx = +k;
          if (isNaN(idx)) return;
          aoa[ri][idx] = row.cells[k].text;
        });
    }
    var ws = utils.aoa_to_sheet(aoa);
    utils.book_append_sheet(out, ws, xws.name);
  });
  return out;
}
function stox(wb) {
  var out = [];
  wb.SheetNames.forEach(function (name) {
    var o = { name: name, rows: {} };
    var ws = wb.Sheets[name];
    var aoa = utils.sheet_to_json(ws, { raw: false, header: 1 });
    aoa.forEach(function (r, i) {
      var cells = {};
      r.forEach(function (c, j) {
        cells[j] = { text: c };
      });
      o.rows[i] = { cells: cells };
    });
    out.push(o);
  });
  return out;
}
</script>
<style scoped>
#luckysheet,
#sheet-wrapper {
  width: 100%;
  height: 90%;
}
</style>
